package top.zhaoyuliu.logbook.server.config;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.tio.client.ClientGroupContext;
import org.tio.client.ReconnConf;
import org.tio.client.intf.ClientAioHandler;
import org.tio.client.intf.ClientAioListener;

import top.zhaoyuliu.logbook.client.utils.ApplicationContextProvider;
import top.zhaoyuliu.logbook.server.connect.client.ClientStart;
import top.zhaoyuliu.logbook.server.connect.server.LbServerAioHandler;
import top.zhaoyuliu.logbook.server.connect.server.LbServerStarter;
import top.zhaoyuliu.logbook.server.properties.LbMailProperties;
import top.zhaoyuliu.logbook.server.properties.LbServiceProperties;

/**
 * Copyright © 2021 Arain. All rights reserved.
 *
 * @Title: LbServiceConfig.java
 * @Prject: logbook-server
 * @Package: top.zhaoyuliu.logbook.server.config
 * @Description: <功能详细描述>
 * @author: Arain
 * @date: 2021年1月22日 下午4:15:54
 * @version: V1.0
 */
@Configuration
@EnableConfigurationProperties({LbServiceProperties.class,LbMailProperties.class})
@ComponentScan("top.zhaoyuliu.logbook.server.*")
public class LbServiceConfig {

	@Bean
	public LbServerStarter lbServerStarter(LbServiceProperties lbServiceProperties,LbMailProperties lbMailProperties) throws IOException {
		lbServiceProperties.setLbMailProperties(lbMailProperties);
		LbServerStarter lbServerStarter = new LbServerStarter(lbServiceProperties);
		lbServerStarter.start();
		return lbServerStarter;
	}

	@Bean
	public ApplicationContextProvider applicationContextProvider() {
		return new ApplicationContextProvider();
	}

	@Bean
	public ClientStart clientStart(LbServiceProperties lbServiceProperties,
			@Autowired(required = false) MongoTemplate mongoTemplate) {
		// handler, 包括编码、解码、消息处理
		ClientAioHandler clientAioHandler = new LbServerAioHandler();
		// 事件监听器，可以为null，但建议自己实现该接口
		ClientAioListener clientAioListener = new top.zhaoyuliu.logbook.server.connect.client.ClientAioListener();
		// 断链后自动连接的，不想自动连接请设为null
		ReconnConf reconnConf = new ReconnConf(5000L, 0);
		ClientGroupContext clientGroupContext = new ClientGroupContext(clientAioHandler, clientAioListener, reconnConf);
		clientGroupContext.setHeartbeatTimeout(0);
		ClientStart start = new ClientStart(clientGroupContext, lbServiceProperties);
		start.setMongoTemplate(mongoTemplate);
		start.start();
		return start;
	}

}
